package com.tfxy.hxl.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
@RequestMapping("/uploads")
public class StaticFileController {

    @Value("${file.upload.path:./uploads/}")
    private String uploadPath;
    @GetMapping("/{filename}")
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        System.out.println("请求访问文件: " + filename);
        System.out.println("上传路径配置: " + uploadPath);
        
        try {
            // 确保上传路径是绝对路径
            File uploadDir = new File(uploadPath);
            if (!uploadDir.isAbsolute()) {
                uploadDir = new File(System.getProperty("user.dir"), uploadPath);
            }
            
            File file = new File(uploadDir, filename);
            System.out.println("文件完整路径: " + file.getAbsolutePath());
            
            if (!file.exists()) {
                System.out.println("文件不存在: " + file.getAbsolutePath());
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(file);
            HttpHeaders headers = new HttpHeaders();
            
            // 根据文件扩展名设置Content-Type
            String contentType = getContentType(filename);
            headers.setContentType(MediaType.parseMediaType(contentType));
            
            System.out.println("文件访问成功，Content-Type: " + contentType);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            System.err.println("文件访问异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }
    
    private String getContentType(String filename) {
        if (filename == null) {
            return "image/jpeg";
        }
        
        String extension = "";
        if (filename.contains(".")) {
            extension = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        }
        
        switch (extension) {
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            case ".gif":
                return "image/gif";
            case ".bmp":
                return "image/bmp";
            case ".webp":
                return "image/webp";
            default:
                return "image/jpeg";
        }
    }
} 